package com.journaldev.threadpool.runner;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * CountDownLatch高级应用-发令枪
 *
 * @author: chenhs
 * @date: Created in 6:42 2019/9/17
 **/
public class RunnerImpl {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        /** 运动员人数*/
        int person = 8;
        /** 裁判*/
        CountDownLatch begin = new CountDownLatch(1);
        /** 跑步*/
        CountDownLatch end = new CountDownLatch(person);

        ExecutorService executorService = new ThreadPoolExecutor(person, person,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

        List<Future<Integer>> list = new ArrayList<>();
        for (int i = 0; i < person; i++) {
            list.add(executorService.submit(new Runner(begin, end)));
        }
        //枪声响起
        begin.countDown();
        //等待所有运动员跑完
        end.await();

        int count = 0;
        int height = 0;
        for (Future<Integer> f : list) {
            count += f.get();
            if (f.get() > height) {
                height = f.get();
            }
        }

        System.out.println("有多少运动员：" + person + "，总分：" + count + "，平均分：" + count / person + "， 最高分：" + height);

        executorService.shutdown();
    }

}
